package com.epfresh.supplier.adapter;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.SortModel;
import com.epfresh.supplier.widget.ViewVariable;
import com.epfresh.supplier.widget.RecyclerViewAdapter;

import java.util.ArrayList;

/**
 * Created by zhuli on 2017/8/16.
 */

public class SortRecycleViewAdapter extends RecyclerViewAdapter<SortModel> implements ViewVariable {


    private String mAction;
    private boolean mIsOrderPermission = true;

    /**
     * 构造方法
     *
     * @param data 数据
     */
    public SortRecycleViewAdapter(ArrayList<SortModel> data) {
        super(data);
    }

    public void setAction(String action) {
        mAction = action;
    }

    public void setOrderPermission(boolean b) {
        mIsOrderPermission = b;
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View view) {
        return new CustomerInfoViewHolder(view, false);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {
        return new CustomerInfoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_customer_contact, parent, false), isItem);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, boolean isItem) {
        CustomerInfoViewHolder viewHolder = (CustomerInfoViewHolder) holder;

        SortModel sortModelItem = getItem(position);

        // 根据position获取分类的首字母的Char ascii值
        int section = getSectionForPosition(position);

        // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
        if (position == getPositionForSection(section)) {
            viewHolder.llLetter.setVisibility(View.VISIBLE);
            viewHolder.tvLetter.setText(sortModelItem.getSortLetters());
        } else {
            viewHolder.llLetter.setVisibility(View.GONE);
        }

        viewHolder.tvName.setText(sortModelItem.getCustomerItem().getName());
        if (TextUtils.isEmpty(sortModelItem.getCustomerItem().getOrg())) {
            viewHolder.tvCompany.setVisibility(View.GONE);
        } else {
            viewHolder.tvCompany.setVisibility(View.VISIBLE);
            viewHolder.tvCompany.setText(sortModelItem.getCustomerItem().getOrg());
        }
        viewHolder.tvTel.setText(sortModelItem.getCustomerItem().getPhone());
    }

    /**
     * 根据rv的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return getItem(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getData().size(); i++) {
            String sortStr = getItem(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 提取英文的首字母，非英文字母用#代替。
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        String sortStr = str.trim().substring(0, 1).toUpperCase();
        // 正则表达式，判断首字母是否是英文字母
        if (sortStr.matches("[A-Z]")) {
            return sortStr;
        } else {
            return "#";
        }
    }


    @Override
    public int getSwipeLayoutResourceId(int i) {
        return 0;
    }

    class CustomerInfoViewHolder extends RecyclerViewHolder {
        LinearLayout llLetter;
        LinearLayout llContact;
        TextView tvLetter;
        TextView tvName;
        TextView tvCompany;
        TextView tvTel;
        TextView tvOrder;


        public CustomerInfoViewHolder(View itemView, boolean isItem) {
            super(itemView, isItem);
            llLetter = (LinearLayout) itemView.findViewById(R.id.item_ll_catalog);
            llContact = (LinearLayout) itemView.findViewById(R.id.item_ll_contact);
            tvLetter = (TextView) itemView.findViewById(R.id.item_tv_catalog);
            tvName = (TextView) itemView.findViewById(R.id.item_tv_name);
            tvCompany = (TextView) itemView.findViewById(R.id.item_tv_company);
            tvTel = (TextView) itemView.findViewById(R.id.item_tv_tel);
            tvOrder = (TextView) itemView.findViewById(R.id.item_tv_order);
            itemView.setOnClickListener(null);
            llContact.setOnClickListener(this);
/*            tvOrder.setOnClickListener(this);todo:
            if (mAction.equals(HOME_ACTIVITY) && mIsOrderPermission) {
                tvOrder.setVisibility(View.VISIBLE);
            } else {
                tvOrder.setVisibility(View.GONE);
            }*/
        }
    }

    /**
     * 目标项是否在最后一个可见项之后
     */
    private boolean mShouldScroll;
    /**
     * 记录目标项位置
     */
    private int mToPosition;
    private RecyclerView mRecyclerView;

    public void smoothMoveToPosition(RecyclerView recyclerView, final int position) {
        this.mRecyclerView = recyclerView;


        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

        if (position < firstItem) {
            // 如果跳转位置在第一个可见位置之前，就smoothScrollToPosition可以直接跳转
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 跳转位置在第一个可见项之后，最后一个可见项之前
            // smoothScrollToPosition根本不会动，此时调用smoothScrollBy来滑动到指定位置
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 如果要跳转的位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll) {
                    mShouldScroll = false;
                    smoothMoveToPosition(mRecyclerView, mToPosition);
                }
            }
        });
    }
}

